<template>
<div class="sku-container">
    <div v-if="!disabled" class="sku-check">
        <div v-if="theme == 1" class="theme-1">
            <el-card v-for="(item, index) in myAttribute" :key="index" class="item" shadow="never">
                <div slot="header" class="sku-header">
                    <div class="title">
                        {{ item.name }}
                    </div>
                    <div class="btn-box">
                        <div class="btn">
                            <el-popconfirm :title="`删除 ${item.name} 属性删除吗？`" @confirm="delSourceAttr(index)">
                                <i slot="reference" class="el-icon-delete" />
                            </el-popconfirm>
                        </div>
                    </div>
                </div>
                <el-checkbox v-for="(item2, index2) in item.item" :key="index2" v-model="item2.checked" :label="item2.label" size="small" />
                <el-input v-if="item.canAddAttribute" v-model="item.addAttribute" size="small" placeholder="新增一个规格" class="add-attr" @keyup.enter.native="onAddAttribute(index)">
                    <el-button slot="append" size="small" icon="el-icon-plus" @click="onAddAttribute(index)">添加</el-button>
                </el-input>
            </el-card>
        </div>
        <el-table v-else :data="myAttribute" :show-header="false" class="theme-2">
            <el-table-column prop="name" width="120" :resizable="false" />
            <el-table-column>
                <template slot-scope="scope">
                    <el-checkbox v-for="(item2, index2) in scope.row.item" :key="index2" v-model="item2.checked" :label="item2.name" size="small" />
                </template>
            </el-table-column>
            <el-table-column width="250">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.addAttribute" size="small" placeholder="新增一个规格" class="add-attr" @keyup.enter.native="onAddAttribute(scope.$index)">
                        <el-button slot="append" size="small" icon="el-icon-plus" @click="onAddAttribute(scope.$index)">添加</el-button>
                    </el-input>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <div class="sku-list">
        <el-form ref="form" :model="form" status-icon inline-message>
            <!-- 批量设置，当 sku 数超过 2 个时出现 -->
            <template v-if="isBatch && form.skuData.length > 2">
                <el-table :data="[{}]" :show-header="false" stripe border highlight-current-row>
                    <el-table-column :width="attribute.length * 120 + 50" align="center" :resizable="false">
                        <el-button type="primary" size="small" @click="onBatchSets">批量设置</el-button>
                        <el-button type="danger" size="small" @click="onBatchEmptys">清空sku内容</el-button>
                    </el-table-column>
                    <el-table-column v-for="(item, index) in structure" :key="`batch-structure-${index}`" align="center" :resizable="false" :width="getItemWidth(item)" :class-name="skuColumnClass(item)">
                        <el-input v-if="item.type == 'input' && item.batch != false" v-model="batch[item.name]" :placeholder="`填写${item.label}`" size="small" @keyup.enter.native="onBatchSet(item.name)" />
                        <template v-if="typeof item.image !='undefined' && item.image && item.batch != false">
                            <div class="el-upload-xs-sm el-upload-view">
                                <template v-if="typeof batch[item.name] == 'object' && batch[item.name].url!=''">
                                    <div v-show="batch[item.name].show" class="upload-list upload-list-center">
                                        <div class="upload-list-item">
                                            <div class="el-upload-img-cover" :style="{'background-image':'url('+batch[item.name].url+')'}">
                                                <span class="el-upload-img-delete" @click="delBatchImage(item.name)">
                                                    <i class="el-icon-error"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                                <template v-if="typeof batch[item.name] != 'object' || batch[item.name].url==''">
                                    <div @onload="batch[item.name]={url:'', filename:'', id:''}" tabindex="0" class="el-upload el-upload--picture-card" @click="uploadImageBySku(item.name)">
                                        <i class="el-icon-plus"></i>
                                        <input type="file" name="file" class="el-upload__input">
                                    </div>
                                </template>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <br v-if="isBatch && form.skuData.length > 2" />
            <el-table :data="form.skuData" :span-method="objectSpanMethod" stripe border highlight-current-row>
                <!-- 考虑到异步加载的情况，如果 attribute 数据先加载完成，则表头会立马展示，效果不理想，故使用emitAttribute 数据，该数据为计算属性，通过 myAttribute 生成，结构与 attribute 一致 -->
                <el-table-column v-if="emitAttribute.length > 0" type="index" width="50" align="center" :resizable="false" />
                <el-table-column v-for="(attr, index) in emitAttribute" :key="`attribute-${index}`" :label="attr.name" :prop="attr.name" width="120" align="center" :resizable="false" sortable />
                <el-table-column v-for="(item, index) in tempStructure" :key="`structure-${index}`" :label="item.label" :prop="item.name" align="center" :resizable="false" :class-name="skuColumnClass(item)" :width="getItemWidth(item)" :min-width="'175px'">
                    <!-- 自定义表头 -->
                    <template slot="header">
                        <span :class="{'required_title': item.required}">
                            {{ item.label }}
                        </span>
                        <el-tooltip v-if="item.tip" effect="dark" :content="item.tip" placement="top">
                            <i class="el-icon-info" />
                        </el-tooltip>
                    </template>
                    <!-- 自定义表格内部展示 -->
                    <template slot-scope="scope">
                        <!-- 增加是 key 是为了保证异步验证不会出现 skuData 数据变化后无法验证的 bug -->
                        <el-form-item v-if="item.type == 'input'" :key="`structure-input-${index}-${scope.row.sku}-input`" :prop="'skuData.' + scope.$index + '.' + item.name" :rules="rules[item.name]">
                            <el-input v-model="scope.row[item.name]" :placeholder="`请输入${item.label}`" size="small" />
                        </el-form-item>
                        <el-form-item v-else-if="item.type == 'slot'" :key="`structure-input-${index}-${scope.row.sku}`" :prop="'skuData.' + scope.$index + '.' + item.name" :rules="rules[item.name]">
                            <slot :name="item.name" :$index="scope.$index" :row="scope.row" :column="scope.column" />
                        </el-form-item>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
    </div>
    <el-dialog class="dialog-uplaod" title="图片库" @opened="imageLibOpenedBySku" :visible.sync="dialogVisible['imageSku']" width="auto" top="10vh" append-to-body>
        <imageLib ref="imageLib" selectedNumMax="1" />
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible['imageSku'] = false">关 闭</el-button>
            <el-button type="danger" @click="getImageBySku">确 定</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
import imageLib from "@/component/helper/fileslib/index";
export default {
    name: 'SkuForm',
    components: {
        imageLib,
    },
    props: {
        /**
         * 原始规格数据
         * sourceAttribute: [
         *   { name: '颜色', item: ['黑', '金', '白'] },
         *   { name: '内存', item: ['16G', '32G'] },
         *   { name: '运营商', item: ['电信', '移动', '联通'] }
         * ]
         */
        sourceAttribute: {
            type: Array,
            default: () => []
        },
        /**
         * 已使用的规格数据，用于复原数据，支持.sync修饰符
         * attribute: [
         *   { name: '颜色', item: ['黑'] },
         *   { name: '运营商', item: ['电信', '移动', '联通'] }
         * ]
         */
        attribute: {
            type: Array,
            default: () => []
        },
        /**
         * 用于复原sku数据，支持.sync修饰符
         * sku: [
         *   { sku: '黑;电信', price: 1, stock: 1 },
         *   { sku: '黑;移动', price: 2, stock: 2 },
         *   { sku: '黑;联通', price: 3, stock: 3 }
         * ]
         */
        sku: {
            type: Array,
            default: () => []
        },
        /**
         * 表格结构，注意name字段，用于输出sku数据
         */
        structure: {
            type: Array,
            default: () => [{
                    name: 'price',
                    type: 'input',
                    label: '价格'
                },
                {
                    name: 'stock',
                    type: 'input',
                    label: '库存'
                }
            ]
        },
        // sku 字段分隔符
        separator: {
            type: String,
            default: ';'
        },
        // 无规格的 sku
        emptySku: {
            type: String,
            default: ''
        },
        // 是否显示 sku 选择栏
        disabled: {
            type: Boolean,
            default: false
        },
        // 主题风格
        theme: {
            type: Number,
            default: 1
        },
        // 是否开启异步加载
        async: {
            type: Boolean,
            default: false
        },
        //属性最大数量
        attributeNumMax: {
            type: Number,
            default: 5
        }
    },
    data() {
        return {
            dialogVisible: {
                imageSku: false,
            },
            isInit: false,
            myAttribute: [],
            form: {
                skuData: []
            },
            batch: {},
            batchImageShow: {},
            batchTempName: '',
            attrCheckedNum: 0,
        }
    },
    computed: {
        rules() {

            // 重新生成验证规则
            let rules = {}
            this.structure.forEach(v => {
                if (v.type == 'input') {
                    rules[v.name] = []
                    if (v.required) {
                        rules[v.name].push({
                            required: true,
                            message: `${v.label}不能为空`,
                            trigger: 'blur'
                        })
                    }
                    if (v.validate) {
                        rules[v.name].push({
                            validator: this.customizeValidate,
                            trigger: 'blur'
                        })
                    }
                } else if (v.type == 'slot') {
                    rules[v.name] = []
                    if (v.required) {
                        rules[v.name].push({
                            required: true,
                            message: `${v.label}不能为空`,
                            trigger: ['change', 'blur']
                        })
                    }
                    if (v.validate) {
                        rules[v.name].push({
                            validator: this.customizeValidate,
                            trigger: ['change', 'blur']
                        })
                    }
                }
            })
            return rules
        },
        isBatch() {
            return this.structure.some(item => {
                return item.type == 'input' && item.batch != false
            })
        },
        // 将 myAttribute 数据还原会 attribute 数据的结构，用于更新 attribute
        emitAttribute() {
            let attribute = []
            // console.log('myAttribute', this.myAttribute);
            this.myAttribute.forEach(v1 => {
                const obj = {
                    name: v1.name,
                    item: []
                }
                v1.item.forEach(v2 => {
                    if (v2.checked) {
                        obj.item.push({
                            label: v2.label,
                            value: null
                        })
                    }
                })

                if (obj.item.length > 0) {
                    attribute.push(obj)
                }
            })
            // console.log('attribute', attribute);
            return attribute
        },
        tempStructure() {
            let structure = []
            // console.log('myAttribute', this.myAttribute);
            this.structure.forEach(v1 => {
                if (typeof v1.hide == 'undefined' || !v1.hide) {
                    structure.push(v1)
                }
            })
            // console.log('attribute', attribute);
            return structure
        },
    },
    watch: {
        myAttribute: {
            handler() {
                if (!this.isInit) {
                    // 更新父组件
                    this.$emit('update:attribute', this.emitAttribute)
                }
                this.attrCheckedNum = this.getAttrCheckedNum()
                // 解决通过 $emit 更新后无法拿到 attribute 最新数据的问题
                this.$nextTick(() => {
                    // console.log('触发sku数据更新');
                    if (this.attribute.length !== 0) {
                        // console.log('this.myAttribute', this.myAttribute);
                        this.combinationAttribute()
                    } else {
                        this.form.skuData = []
                        const obj = {
                            sku: this.emptySku
                        }
                        this.structure.forEach(v => {
                            if (!(v.type == 'slot' && v.skuProperty == false)) {
                                obj[v.name] = typeof v.defaultValue != 'undefined' ? v.defaultValue : ''
                            }
                        })
                        this.form.skuData.push(obj)
                    }
                    this.clearValidate()
                })
            },
            deep: true
        },
        'form.skuData': {
            handler(newValue, oldValue) {
                if (!this.isInit || (newValue.length == 1 && newValue[0].sku == this.emptySku)) {
                    // 如果有老数据，或者 sku 数据为空，则更新父级 sku 数据
                    if (oldValue.length || !this.sku.length) {
                        // 更新父组件
                        const arr = []
                        newValue.forEach(v1 => {
                            const obj = {
                                sku: v1.sku
                            }
                            this.structure.forEach(v2 => {
                                if (!(v2.type == 'slot' && v2.skuProperty == false)) {
                                    obj[v2.name] = v1[v2.name] || (typeof v2.defaultValue != 'undefined' ? v2.defaultValue : '')
                                }
                            })
                            arr.push(obj)
                        })
                        //this.$emit('update:sku', arr)
                    }
                }
                if (!this.isInit) {
                    const arr = [];
                    this.form.skuData.forEach(v1 => {
                        const obj = {
                            sku: v1.sku
                        }
                        this.structure.forEach(v2 => {
                            if (!(v2.type == 'slot' && v2.skuProperty == false)) {
                                obj[v2.name] = v1[v2.name] || (typeof v2.defaultValue != 'undefined' ? v2.defaultValue : '')
                            }
                        })
                        arr.push(obj)
                    })
                    this.$emit('update:sku', arr)
                }

            },
            deep: true
        }
    },
    mounted() {
        !this.async && this.init()
    },
    methods: {
        //获取列宽度
        getItemWidth(item) {
            if (typeof item.hide != 'undefined' || item.hide) {
                return '0px'
            }

            if (typeof item.width != 'undefined') {
                return typeof item.width == 'string' ? item.width : item.width + 'px'
            }
            return '120px'
        },
        //sku图片上传
        uploadImageBySku(name) {
            this.batchTempName = name
            this.dialogVisible['imageSku'] = true
        },
        //sku图片库打开回调
        imageLibOpenedBySku() {
            this.$refs.imageLib.getData()
        },
        //获取sku图片
        getImageBySku() {
            let list = this.$refs.imageLib.getSelectedList(true)
            if (list.length > 0) {
                this.dialogVisible['imageSku'] = false
                this.batch[this.batchTempName] = {
                    show: true,
                    url: list[0].url,
                    filename: list[0].filename,
                    id: list[0].id
                }
                // console.log(this.batch[this.batchTempName]);
            } else {
                this.$message.info('未选择有效图片')
            }
        },
        //删除批量的图片
        delBatchImage(name) {
            this.batch[name].url = '';
            this.batch[name].show = false;
            // console.log('row', this.batch[name])
            this.$forceUpdate();
        },
        skuColumnClass(item) {
            return typeof item.hide == 'undefined' || !item.hide ? '' : 'hide';
        },
        init() {
            //console.log('this.sku', this.sku)
            //沉梦优化版 保留属性、规格的原始结构数据方便保存数据
            this.$nextTick(() => {
                this.isInit = true
                // 初始化 myAttribute
                let myAttribute = []
                // 根据 sourceAttribute 复原 myAttribute 的结构
                this.sourceAttribute.forEach(v => {
                    v = Object.assign({
                        name: v.name,
                        canAddAttribute: typeof v.canAddAttribute != 'undefined' ? v.canAddAttribute : true,
                        addAttribute: '',
                    }, v)

                    v.item.forEach(itemObj => {
                        return Object.assign(this.objectCopy(itemObj), {
                            label: typeof itemObj.label != 'undefined' ? itemObj.label : itemObj.name,
                            checked: typeof itemObj.checked != 'undefined' ? itemObj.checked : false,
                        });
                    })
                    myAttribute.push(this.objectCopy(v))
                })
                // console.log('this.sku[0]', this.sku[0]);
                //console.log('myAttribute', myAttribute);
                // 根据 attribute 更新 myAttribute
                this.attribute.forEach(attrVal => {
                    myAttribute.forEach(myAttrVal => {
                        if (attrVal.name === myAttrVal.name) {
                            attrVal.item.forEach(attrItem => {
                                if (
                                    !myAttrVal.item.some(myAttrItem => {
                                        if (attrItem.label === myAttrItem.label) {
                                            myAttrItem.checked = true
                                        }
                                        return attrItem.label != '' && attrItem.label === myAttrItem.label
                                    })
                                ) {
                                    attrItem.checked = typeof attrItem.checked != 'undefined' ? attrItem.checked : false;
                                    myAttrVal.item.push(attrItem)
                                }
                            })

                        }
                    })
                })
                //console.log('this.sku[0]', this.sku[0]);
                //console.log('myAttribute', myAttribute);
                this.myAttribute = myAttribute
                //console.log('this.sku[0]', this.sku[0]);
                // 通过 sku 更新 skuData，但因为 skuData 是实时监听 myAttribute 变化并自动生成，而 watch 是在 methods 后执行，所以增加 setTimeout 方法，确保 skuData 生成后在执行下面的代码
                setTimeout(() => {
                    //console.log('this.sku[0]', this.sku[0]);
                    this.sku.forEach(skuItem => {
                        this.form.skuData.forEach(skuDataItem => {
                            if (skuItem.sku === skuDataItem.sku) {
                                this.structure.forEach(structureItem => {
                                    skuDataItem[structureItem.name] = skuItem[structureItem.name]
                                })
                            }
                        })
                    })
                    //console.log('this.sku', this.sku);
                    this.isInit = false
                }, 0)
            })
        },
        //删除属性
        delSourceAttr(index) {
            this.$delete(this.myAttribute, index);
        },
        //合并重复单元行 使sku组合展示更简洁易懂 By 沉梦
        objectSpanMethod({
            row,
            column,
            rowIndex,
            columnIndex
        }) {
            let obj = null
            //console.log('columnIndex', columnIndex)
            //console.log('this.attrCheckedNum', this.attrCheckedNum)
            this.myAttribute.forEach((item, i) => {
                // 此处注意 最后一个有效选中属性属于最小规格，所以不用合并 columnIndex < this.myAttribute.length
                // 此处注意 属性的规格数量应该大于0   所以 item.item.length > 0
                if (columnIndex === i + 1 && columnIndex < this.attrCheckedNum && item.item.length > 0) {
                    //获取该规格可组合多少次 根据组合次数来取得合并数量
                    let rowsNum = this.getRowsNum(i)
                    if (rowsNum > 0) {
                        // console.log('求余', (rowIndex + rowsNum) % rowsNum);
                        if ((rowIndex + rowsNum) % rowsNum === 0) {
                            obj = {
                                rowspan: rowsNum,
                                colspan: 1
                            };
                        } else {
                            obj = {
                                rowspan: 0,
                                colspan: 0
                            };
                        }

                    }
                }
            });
            if (obj != null) {
                return obj
            }
        },
        //获取被有效勾选的属性数量
        getAttrCheckedNum() {
            let num = 0
            this.myAttribute.forEach(item => {
                let checkedNum = this.getCheckedNum(item.item)
                if (checkedNum > 0) {
                    num++
                }
            });
            return num
        },
        //获取该规格跟后面的属性规格可组合多少次
        getRowsNum(index) {
            let num = 1
            this.myAttribute.forEach((item, i) => {
                // let  emptyNum = 0  修复多个属性中间有一个规格没选中的属性时合并过多bug
                let emptyNum = this.getLimitEmptyNum(0, i);
                if (i > (index + emptyNum)) {
                    let checkedNum = this.getCheckedNum(item.item)
                    //此处注意 选中规格数量应大于0 不然会出bug
                    if (checkedNum > 0) {
                        num = checkedNum * num
                    }
                }
            });
            return num
        },
        //获取中间未选中的属性数量
        getLimitEmptyNum(start, end) {
            let num = 0
            this.myAttribute.forEach((item, i) => {
                if (i > start && i < end) {
                    let checkedNum = this.getCheckedNum(item.item)
                    //此处注意 选中规格数量应大于0 不然会出bug
                    if (checkedNum == 0) {
                        num++
                    }
                }
            });
            return num
        },
        //获取属性中的选中规格的数量
        getCheckedNum(item) {
            if (!Array.isArray(item)) {
                return 0
            }
            let num = 0
            item.forEach(v => {
                if (v.checked) {
                    num++;
                }
            });
            return num
        },
        // 根据 attribute 进行排列组合，生成 skuData 数据
        combinationAttribute(index = 0, dataTemp = []) {
            // console.log('index', index);
            if (index === 0) {
                for (let i = 0; i < this.attribute[0].item.length; i++) {
                    const obj = {
                        sku: this.attribute[0].item[i].label,
                        [this.attribute[0].name]: this.attribute[0].item[i].label
                    }
                    this.structure.forEach(v => {
                        if (!(v.type == 'slot' && v.skuProperty == false)) {
                            obj[v.name] = typeof v.defaultValue != 'undefined' ? v.defaultValue : ''
                        }
                    })
                    dataTemp.push(obj)
                }
                //console.log('dataTemp', dataTemp);
            } else {
                const temp = []
                for (let i = 0; i < dataTemp.length; i++) {
                    //取出原sku信息
                    let item = JSON.parse(JSON.stringify(dataTemp[i]));
                    //新组合容器
                    let rows = []
                    for (let j = 0; j < this.myAttribute[index].item.length; j++) {
                        //优化 没有选中也会加入sku的bug
                        if (this.myAttribute[index].item[j].checked) {
                            let itemTemp = JSON.parse(JSON.stringify(item));
                            itemTemp[this.myAttribute[index].name] = this.myAttribute[index].item[j].label
                            itemTemp['sku'] = [itemTemp['sku'], this.myAttribute[index].item[j].label].join(this.separator)
                            rows.push(itemTemp);
                            //console.log('itemTemp', itemTemp);
                        }
                    }
                    //如果新属性的组合大于0 则合并 否则不变
                    if (rows.length > 0) {
                        for (let index = 0; index < rows.length; index++) {
                            temp.push(rows[index])
                        }
                    } else {
                        temp.push(item)
                    }
                }
                dataTemp = temp

            }

            if (index !== this.myAttribute.length - 1) {
                this.combinationAttribute(index + 1, dataTemp)
            } else {
                if (!this.isInit || this.async) {
                    // 将原有的 sku 数据和新的 sku 数据比较
                    // 相同的 sku 则把原有的 sku 数据覆盖到新的 sku 数据里
                    for (let i = 0; i < this.form.skuData.length; i++) {
                        for (let j = 0; j < dataTemp.length; j++) {
                            if (this.form.skuData[i].sku === dataTemp[j].sku) {
                                dataTemp[j] = this.form.skuData[i]
                            }
                        }
                    }
                }
                this.form.skuData = dataTemp
                //console.log('this.form.skuData', this.form.skuData);
            }
        },
        //新增一个属性
        onAddAttr(attrName) {
            console.log()
            if (this.myAttribute.length >= this.attributeNumMax) {
                this.$message({
                    type: 'danger',
                    message: `属性最多添加只能${this.attributeNumMax}组`
                })
                return;
            }

            this.myAttribute.push({
                name: attrName,
                canAddAttribute: true,
                item: []
            })
        },
        // 新增一个规格
        onAddAttribute(index) {
            this.myAttribute[index].addAttribute = this.myAttribute[index].addAttribute.trim()
            if (this.myAttribute[index].addAttribute !== '') {
                if (!this.myAttribute[index].addAttribute.includes(this.separator)) {
                    const flag = this.myAttribute[index].item.some(item => {
                        return item.label === this.myAttribute[index].addAttribute
                    })

                    if (!flag) {
                        this.myAttribute[index].item.push({
                            label: this.myAttribute[index].addAttribute,
                            checked: true
                        })
                        this.myAttribute[index].addAttribute = ''
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '请勿添加相同规格'
                        })
                    }

                } else {
                    this.$message({
                        type: 'warning',
                        message: `规格里不允许出现「 ${this.separator} 」字符，请检查后重新添加`
                    })
                }
            }
        },
        //更新attribute
        updateAttribute() {

        },
        onBatchSet(type) {
            if (this.batch[type] != '') {
                this.form.skuData.forEach(v => {
                    v[type] = this.batch[type]
                })
                this.batch[type] = ''
                // 批量设置完成后，触发一次当前列的验证
                this.validateFieldByColumns([type], () => {})
            }
        },
        //批量设置
        onBatchSets() {
            Object.keys(this.batch).forEach((type, key) => {
                this.form.skuData.forEach(v2 => {
                    if (this.batch[type] && v2[type] == '') {
                        //对象复制
                        if (typeof this.batch[type] == 'object') {
                            v2[type] = this.objectCopy(this.batch[type])
                        } else {
                            v2[type] = this.batch[type]
                        }
                    }
                })
                this.batch[type] = ''
                // 批量设置完成后，触发一次当前列的验证
                this.validateFieldByColumns([type], () => {})
            });
        },
        //清空sku内容
        onBatchEmptys() {
            let headList = [];
            this.myAttribute.forEach(v => {
                headList.push(v.name)
            });
            console.log('window.Array', window.Array());
            this.form.skuData.forEach(v2 => {
                Object.keys(v2).forEach(type => {
                    if (!headList.inArray(type)) {
                        v2[type] = '';
                    }
                });
                return v2
            })
        },
        // 自定义输入框验证，通过调用 structure 里的 validate 方法实现，重点是 callback 要带过去
        customizeValidate(rule, value, callback) {
            let [model, index, name] = rule.field.split('.')
            this.structure.forEach(v => {
                if (v.name == name) {
                    v.validate(this.form[model], index, callback)
                }
            })
        },
        // sku 表单验证
        validate(callback) {
            this.$refs['form'].validate(valid => {
                callback(valid)
            })
        },
        validateFieldByColumns(colums, callback) {
            let props = []
            this.form.skuData.forEach((v, i) => {
                colums.forEach(v => {
                    props.push(`skuData.${i}.${v}`)
                })
            })
            this.$refs['form'].validateField(props, valid => {
                callback(valid)
            })
        },
        validateFieldByRows(index, prop, callback) {
            this.$refs['form'].validateField([`skuData.${index}.${prop}`], valid => {
                callback(valid)
            })
        },
        clearValidate() {
            this.$refs['form'].clearValidate()
        }
    }
}
</script>

<style lang="scss" scoped>
.el-card>.el-card__body>.el-checkbox {
    margin-right: 10px;
}

.sku-container {
    margin-top: 5px;

    ::v-deep .el-card {
        margin: 10px 0;

        .el-card__header {
            line-height: initial;
            padding: 10px 20px;
        }

        .el-card__body {
            padding: 10px 20px 20px;
        }
    }

    .sku-header {
        display: flex;

        >.title {
            flex: 1;
        }

        >.btn-box {
            flex: 1;

            >.btn {
                float: right;
            }
        }
    }

    .sku-check {
        .theme-1 {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            margin-bottom: 10px;

            .item {
                width: 32%;

                &:last-child:nth-child(3n - 1) {
                    margin-right: calc(100% - 32% * 2 - 4% / 2) !important;
                }

                .add-attr {
                    width: 100%;
                    margin-top: 10px;
                }
            }
        }

        .theme-2 {
            border: 1px solid #ebeef5;
            border-bottom: 0;
            margin-bottom: 20px;
        }
    }

    .sku-name {
        text-align: right;
    }

    .batch-set {
        width: 100%;
        margin-top: 5px;
    }

    .sku-list {
        line-height: initial;

        ::v-deep .el-input__inner {
            text-align: center;
        }

        ::v-deep .el-table__append-wrapper {
            overflow: initial;

            .el-table {
                overflow: initial;

                .el-table__body-wrapper {
                    overflow: initial;
                }
            }
        }

        ::v-deep .el-form-item {
            margin-bottom: 0;

            .el-form-item__content {
                line-height: initial;

                .el-form-item__error {
                    margin-left: 0;
                }
            }
        }

        .required_title::before {
            content: '*';
            color: #f56c6c;
        }
    }
}
</style>
